package com.webchat.netty.server.handler;

import com.webchat.netty.server.service.UserChannelManager;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.QueryStringDecoder;
import io.netty.util.AttributeKey;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Map;

import static com.webchat.common.constants.NettySocketConstants.CHAT_WEBSOCKET_PATH;
import static com.webchat.common.constants.NettySocketConstants.QUERY_BIZ_CODE;
import static com.webchat.common.constants.NettySocketConstants.QUERY_USER_ID;


@Slf4j
public class NettyWebSocketRequestHandler extends SimpleChannelInboundHandler<FullHttpRequest> {


    @Override
    protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {

        QueryStringDecoder queryStringDecoder = new QueryStringDecoder(request.uri());
        Map<String, List<String>> parameters = queryStringDecoder.parameters();

        // 从请求中获取query参数（业务参数）
        String userId = parameters.getOrDefault(QUERY_USER_ID, List.of("")).get(0);
        // 保存到handler链式处理上下文
        ctx.channel().attr(AttributeKey.valueOf(QUERY_USER_ID)).set(userId);

        // 注册用户连接实例信息、管理用户channel
        UserChannelManager.addChannel(userId, ctx.channel());
        UserChannelManager.registryInstance(userId);

        // 处理技巧(处理后续的协议升级)
        request.setUri(CHAT_WEBSOCKET_PATH);
        // 很关键，重新修改后的request需要传给后续调用链
        ctx.fireChannelRead(request.retain());
    }
}
